// pages/pay/index.js
import { axios } from "../../request";
import regeneratorRuntime from "../../libs/runtime";
Page({
  /**
   * 页面的初始数据
   */
  data: {
    siteObj: {
      details: "",
      name: "",
      phone: ""
    },
    cartList: {}
  },
  // 获取地理信息点击
  getSiteClick() {
    // 获取用户信息。
    wx.getSetting({
      success: res => {
        const scopeAddress = res.authSetting["scope.address"];
        // console.log('收货地址授权情况', scopeAddress);
        // 三情况的返回值
        // true      授权
        // false     拒绝授权
        // undefind  还没调用过接口（主动调用）
        if (scopeAddress || scopeAddress === undefined) {
          console.log("进来");
          wx.chooseAddress({
            success: res => {
              // 获取用户收货地址。调起用户编辑收货地址原生界面，并在编辑完成后返回用户选择的地址。
              const {
                provinceName,
                cityName,
                countyName,
                detailInfo,
                userName,
                telNumber
              } = res;
              // 准备存进 本地缓存 和 setdata的对象
              const siteObj = {
                details: provinceName + cityName + countyName + detailInfo,
                name: userName,
                phone: telNumber
              };
              this.setData({
                siteObj
              });
              // 存进本地缓存
              wx.setStorageSync("site", siteObj);
            }
          });
        } else {
          wx.openSetting({
            success(res) {
              // console.log("res设置: ", res);
            }
          });
        }
      }
    });
  },
  onShow() {
    this.getLocalCartList();
    const siteObj = wx.getStorageSync("site") || {};
    // 判断数据是否存在
    this.setData({
      siteObj
    });
  },
  // 获取本地购物车列表
  getLocalCartList() {
    let cart = wx.getStorageSync("cart");
    // console.log('cart: ', cart);
    cart = cart.filter(item => {
      return item.isSelect;
    });
    // console.log('cart: ', cart);
    this.setData({
      cartList: cart
    });
  },
  // 去结算按钮
  async goToPay(e) {
    const { siteObj } = this.data;
    // 没有填地址
    if (!(siteObj.details && siteObj.name && siteObj.phone)) {
      wx.showToast({
        title: "您还没有输入收货信息",
        icon: "none"
      });
      return;
    }
    // 获取本地缓存 token
    const token = wx.getStorageSync("token") || "";
    // 没有登录 跳转到授权页面
    if (!token) {
      // 小程序showToast和navigateTo同时使用
      // https://blog.csdn.net/weixin_43687896/article/details/84665225
      wx.showToast({
        title: "请先登录",
        icon: "loading",
        duration: 800
      });
      setTimeout(() => {
        wx.navigateTo({
          url: "/pages/auth/index"
        });
      }, 800);
    }

    if (token) {
      const { cartList } = this.data;
      // axios请求data
      const cartAxios = { goods: [] }; //goods 订单数组
      // 总价格计算
      let order_price = 0;
      cartList.forEach(element => {
        if (element.isSelect) {
          order_price += +element.goods_price;
          cartAxios.goods.push({
            goods_id: element.goods_id,
            goods_number: element.number,
            goods_price: element.goods_price
          });
        }
      });
      // 收货地址
      cartAxios.consignee_addr = siteObj.details;
      cartAxios.order_price = order_price;
      try {
        const res = await axios({
          method: "POST",
          url: "/my/orders/create",
          data: cartAxios
        });
        // console.log('res: ', res);
        // 订单编号
        const { order_number } = res.message;
        // 获取支付参数
        const res2 = await axios({
          method: "POST",
          url: "/my/orders/req_unifiedorder",
          data: { order_number }
        });
        // 调起微信支付接口
        const res3 = await wx.requestPayment({ ...res2.message.pay });
        // console.log("res: 支付成功", res3);
        // errMsg: "requestPayment:ok"
    // 调用购买完成函数
      this.setLocalBuyOk()

      } catch (error) {
        console.log("支付失败");
        wx.showToast({
          title: "支付异常 请重试",
          icon: "none",
          duration: 800
        });
      }
    }
  },
  // 购买完成
  setLocalBuyOk(){
    let cart = wx.getStorageSync('cart');
    cart = cart.filter(item=>!item.isSelect)
    wx.setStorageSync('cart',cart)
    // 跳转到新页面 从页面栈中删除当前函数
    wx.redirectTo({
      url:"/pages/order/index"
    })
  },
});